<?php

Yii::import('application.models._base.BaseCogs');

class Cogs extends BaseCogs
{
	public static function model($className=__CLASS__) {
		return parent::model($className);
	}
    public static function count_biaya_beli($tgl,$pembelian_id,$barang_id,$unit,$harga){
        $barang = Barang::model()->findByPk($barang_id);
        $jml_stok = StockMoves::count_barang($barang_id);
        if($jml_stok < 0){
            $jml_stok = 0;
        }
        $harga_lama = $barang->price_buy;
        $total_lama = $jml_stok * $harga_lama;
        $total_baru = $unit * $harga;
        $jml_baru = $jml_stok + $unit;
        $harga_baru = ($total_baru + $total_lama) / $jml_baru;
        $barang->price_buy = $harga_baru;
        if(!$barang->save()){
            throw new Exception("Gagal menyimpan barang.".CHtml::errorSummary($barang));
        }
        $cogs = new Cogs;
        $cogs->tgl = $tgl;
        $cogs->pembelian_id = $pembelian_id;
        $cogs->barang_id = $barang_id;
        $cogs->jml = $unit;
        $cogs->cogs = $harga_baru;
        $cogs->total = $total_baru;
        $cogs->harga = $harga;
        if(!$cogs->save()){
            throw new Exception("Gagal menyimpan cogs.".CHtml::errorSummary($cogs));
        }
    }
}